package time_20230811;

/**
 * @author lizhen
 * @date 2023/8/11 17:15
 */

/**
 * 14.最长公共前缀
 */
public class LongestCommonPrefix {
    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        String res = longestCommonPrefix(strs);
        System.out.println(res);
    }

    public static String longestCommonPrefix(String[] strs){
        if (strs == null || strs.length == 0){
            return "";
        }

        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            prefix = longestCommonPrefixInTwo(prefix, strs[i]);
            if (prefix.length() == 0){
                break;
            }
        }

        return prefix;
    }

    public static String longestCommonPrefixInTwo(String s1, String s2) {
        int length = Math.min(s1.length(), s2.length());
        int index = 0;
        while (index < length && s1.charAt(index) == s2.charAt(index)) {
            index++;
        }

        return s1.substring(0, index);
    }
}
